<script setup lang="ts">
import {onMounted, ref, watch} from 'vue'
import {useRoute} from "vue-router";
import {updateUserInfo, userCurrent} from "@/api/UserApi";
import {showFailToast, showSuccessToast} from "vant";
import router from "@/router";
import {getCurrentUser} from "@/services/user";

const route = useRoute()

const editUser = ref({
  editKey: route.query.editKey || '',
  editLabel: route.query.editLabel || '',
  currentValue: route.query.currentValue || '',
});
console.log(route.query)

// 监听路由参数变化，实时更新
watch(
    () => route.query,
    (newQuery) => {
      editUser.value = {
        editKey: newQuery.editKey || '',
        editLabel: newQuery.editLabel || '',
        currentValue: newQuery.currentValue || '',
      };
    }
);

// 修改用户信息
const onSubmit = async (user: any, loginUser: any) => {
  const currentUser = await getCurrentUser();
  if (!currentUser) {
    return;
  }
  const res = await updateUserInfo(editUser.value.currentValue, loginUser);
  if (res.data.code === 0) {
    showSuccessToast('修改成功');
    router.back();
  } else {
    showFailToast('修改失败');
  }

};

const afterRead = (file: any) => {
  // 此时可以自行将文件上传至服务器
  console.log(file);
};


</script>

<template>
  <br/>
  <div>
    <van-form>
      <van-cell-group inset>
        <van-field v-if="editUser.editKey !== 'avatarUrl'"
                   v-model="editUser.currentValue"
                   :name="`${editUser.editLabel || '编辑内容'}：`"
                   :label="editUser.editLabel + '：'"
                   :placeholder="`请输入${editUser.editLabel}：`"
        >
        </van-field>
        <van-uploader :after-read="afterRead" v-else/>

      </van-cell-group>
      <div style="margin: 16px;">
        <van-button @click="onSubmit()" round block type="primary"
                    native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
</style>
